<template>
  <el-switch
    v-model="value"
    :active-value="true"
    :inactive-value="false"
    inline-prompt
    :disabled="disabled"
    :loading="loading"
    :active-color="activeColor"
    @change="onClick"
  />
</template>

<script setup lang="ts">
interface IProps {
  modelValue: number | boolean | undefined
  disabled?: boolean
  activeColor?: string
  // 需要使用loading时，换成下面的调用方式
  loadingChange?: () => Promise<any>
}
interface IEmits {
  (event: 'click'): void
  (event: 'update:modelValue', value: number): void
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmits>()

const loading = ref(false)

const value = computed({
  get() {
    return props.modelValue
  },
  set(value: number) {
    emit('update:modelValue', value)
  }
})

function onClick() {
  if (props.disabled || loading.value) return
  emit('click')
  if (props.loadingChange) {
    loading.value = true
    props.loadingChange().finally(() => {
      loading.value = false
    })
  }
}
</script>
